<?php


function Get_user_by_condition($phone){
      $User = M('user','e_','ecrm');
      $where['user_cell'] = $phone;
      // 把查询条件传入查询方法
      $data= $User->where($where)->find();
      return $data;
}

function Get_user_by_email($phone){
      $User = M('user','e_','ecrm');
      $where['email'] = $phone;
      // 把查询条件传入查询方法
      $data= $User->where($where)->find();
      return $data;
}
/**
 * Created by PhpStorm.
 * User: cyy
 * Date: 2016/11/22
 * Time: 18:05
 */
/**
/**
 * 时间差计算
 *
 * @param Timestamp $time
 * @return String Time Elapsed
 * @author Shelley Shyan
 * @copyright http://phparch.cn (Professional PHP Architecture)
 */
function diffBetweenTwoDays ($day1, $day2)
{
//      $second1 = strtotime($day1);
//      $second2 = strtotime($day2);

      if ($day1 < $day2) {
            $tmp = $day2;
            $second2 = $day1;
            $second1 = $tmp;
      }
      return ($second1 - $second2) / 86400;
}
function time2Units ($enddate,$startdate)
{
//      $year   = floor($time / 60 / 60 / 24 / 365);
//      $time  -= $year * 60 * 60 * 24 * 365;
//      $month  = floor($time / 60 / 60 / 24 / 30);
//      $time  -= $month * 60 * 60 * 24 * 30;
//      $week   = floor($time / 60 / 60 / 24 / 7);
//      $time  -= $week * 60 * 60 * 24 * 7;
//      $day    = floor($time / 60 / 60 / 24);
//      $time  -= $day * 60 * 60 * 24;
//      $hour   = floor($time / 60 / 60);
//      $time  -= $hour * 60 * 60;
//      $minute = floor($time / 60);
//      $time  -= $minute * 60;
//      $second = $time;
//      $elapse = '';
//
//      $unitArr = array('年'  =>'year', '个月'=>'month',  '周'=>'week', '天'=>'day',
//            '小时'=>'hour', '分钟'=>'minute', '秒'=>'second'
//      );
//
//      foreach ( $unitArr as $cn => $u )
//      {
//            if ( $$u > 0 )
//            {
//                  $elapse = $$u . $cn;
//                  break;
//            }
//      }
//      $str = preg_replace( '/[^\d]/ ', ' ',$elapse);
//      return $str;
      $days=round(($enddate-$startdate)/3600/24) ;

      echo $days; //days为得到的天数;
}
/**
 * 签到写入数据库
 *  @param mixed  $uid uid
 * @param mixed  $isbreak isbreak  1断签
 */
  function  writeSign($uid,$isbreak){
      $Sign=D('Sign');
      $data['create_time'] = strtotime(date("Y-m-d"));
      $data['uid'] = $uid;
        if(!empty($isbreak)){
              $data['isbreak'] = $isbreak;//记录他断签标记
        }
      $data['ismobile']=isMobile()==true?"手机端":"pc端";
      $Sign->create($data);
      if($Sign->add($data)){
            \Think\Log::write('签到成功 时间为：'.date("Y-m-d"),'INFO');
      } else {
            echo $Sign->getError();
      }
}

/**
 * 增加积分操作 需要记录到狮友汇 那边的积分日志里面
 * @param mixed  $uid uid
 * @param mixed  $score 用户积分
 * @param mixed  $operator_type 操作类型 1增加 2扣减
 * $@param mixed   $itemId 积分类型
 *
 */
function GetQdBytime($time){
             if(cookie("uid")!=null || cookie("nick_name")!=null){
                   $M = M('sign','ny_','newyear');
                   $where['uid'] = cookie("uid");
                   $userSign=$M->where("uid=".cookie("uid") ." and create_time=".$time )->find();
                   return $userSign;
             }else{
                   return null;
             }



}



/**
 * 增加积分操作 需要记录到狮友汇 那边的积分日志里面
 * @param mixed  $uid uid
 * @param mixed  $score 用户积分
 * @param mixed  $operator_type 操作类型 1增加 2扣减
 * $@param mixed   $itemId 积分类型
 *
 */
  function  Add_user_points($uid,$score,$operator_type,$itemId){
      //扣除积分
//        echo "增加了".$score."积分";
       $M = M('point','e_user_','ecrm');
       $where['user_id'] = $uid;
      // 把查询条件传入查询方法
       $point= $M->where($where)->find();
       if($point==null || empty($point)){//积分记录没有
              $pointData['user_id']=$uid;
              $pointData['currency_point']=5;
              $pointData['total_currency']=5;
              $pointData['currency_last_modtime']=time();
              $pointData['currency_last_detailid']=$itemId;
              $M->add($pointData);
              $currPoint=0;
        }else{
              $currPoint=$point['currency_point']; //获取用户的当前积分
              $total_currency=$point['total_currency']; //获取用户的当前zong 积分
        }
      unset($M);
      $M = M('point','e_user_','ecrm');
      // 要修改的数据对象属性赋值
      if($operator_type==1){
              $UserScore=$currPoint+$score;
              $UserTotalScore=$total_currency+$score;
              $where['currency_point'] = $UserScore;
              $where['total_currency'] = $UserTotalScore;
        } if($operator_type==2){
              $UserScore= $currPoint-$score;
              $UserTotalScore=$total_currency-$score;
              $where['currency_point'] = $UserScore;
              $where['total_currency'] = $UserTotalScore;
        }
       $M->where('user_id='.$uid)->save($where); // 根据条件更新记录
        ////记录到狮友汇 那边的积分日志里面
        ecrm_pointDetil($uid,$itemId,$score,$operator_type);
}

/**
 * ecrm itemID 日志
 * @param mixed  $uid uid
 * @param mixed  $socre 用户积分
 * @param mixed  $operator_type 操作类型 1增加 2扣减
 * $@param mixed   $itemId 积分类型
 */
  function  ecrm_pointDetil($uid,$itemId,$socre,$operator_type){
      $M = M('pointdetail','e_user_','ecrm');
      $log['user_id'] = $uid;
      $log['point_item_type'] = 1;
      $log['point_item_id'] = $itemId;
      $log['operator_type'] = $operator_type;
      $log['point_value'] = $socre;
      $log['create_time'] =time();
      $M->add($log);
}

/*
 * 经典的概率算法，2
 */

function get_rand2($proArr) {
      $proSum = array_sum($proArr);
      $randNum = mt_rand(1, $proSum);
      foreach($proArr as $key => $proCur) {
            $proSum -= $proCur;
            if($randNum > $proSum) {
                  return $key;
            }
      }
}
function get_pname($prize_arr,$rid){

      foreach($prize_arr  as $key=>$value){
            if($value['pid']==$rid){
                  $res['yes'] = $value['prize']; //中奖项
                  break;
            }
      }
      return $res['yes'];
}

/**
 * 是否移动端访问访问
 *
 * @return bool
 */
function isMobile()
{
      // 如果有HTTP_X_WAP_PROFILE则一定是移动设备
      if (isset ($_SERVER['HTTP_X_WAP_PROFILE']))
      {
            return true;
      }
      // 如果via信息含有wap则一定是移动设备,部分服务商会屏蔽该信息
      if (isset ($_SERVER['HTTP_VIA']))
      {
            // 找不到为flase,否则为true
            return stristr($_SERVER['HTTP_VIA'], "wap") ? true : false;
      }
      // 脑残法，判断手机发送的客户端标志,兼容性有待提高
      if (isset ($_SERVER['HTTP_USER_AGENT']))
      {
            $clientkeywords = array ('nokia',
                  'sony',
                  'ericsson',
                  'mot',
                  'samsung',
                  'htc',
                  'sgh',
                  'lg',
                  'sharp',
                  'sie-',
                  'philips',
                  'panasonic',
                  'alcatel',
                  'lenovo',
                  'iphone',
                  'ipod',
                  'blackberry',
                  'meizu',
                  'android',
                  'netfront',
                  'symbian',
                  'ucweb',
                  'windowsce',
                  'palm',
                  'operamini',
                  'operamobi',
                  'openwave',
                  'nexusone',
                  'cldc',
                  'midp',
                  'wap',
                  'mobile'
            );
            // 从HTTP_USER_AGENT中查找手机浏览器的关键字
            if (preg_match("/(" . implode('|', $clientkeywords) . ")/i", strtolower($_SERVER['HTTP_USER_AGENT'])))
            {
                  return true;
            }
      }
      // 协议法，因为有可能不准确，放到最后判断
      if (isset ($_SERVER['HTTP_ACCEPT']))
      {
            // 如果只支持wml并且不支持html那一定是移动设备
            // 如果支持wml和html但是wml在html之前则是移动设备
            if ((strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') !== false) && (strpos($_SERVER['HTTP_ACCEPT'], 'text/html') === false || (strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') < strpos($_SERVER['HTTP_ACCEPT'], 'text/html'))))
            {
                  return true;
            }
      }
      return false;
}

/**
 *
 * 登陆日志
 * @param uid 用户id
 */
  function  log_login($uid){
      $M = M('log','ny_login_','newyear');
      $log['uid'] = $uid;
      $log['strip'] =get_client_ip();
      $log['addtime'] =time();
      $M->add($log);
}

/**
 * 检查 是否登陆
 * @return Boolean
 */
function checkIsLogin(){
      //检测是否登录状态
      $uid = cookie('uid');
      $nick_name = cookie('nick_name');
      $email = cookie('email');
      if($uid=="" || $nick_name=="" || $email=="" || $uid==null || $nick_name==null || $email==null){
         return true;
      }
         return false;
}

/**
 * 通过uid
 * 获取用户的积分
 * @param uid $uid
 * @return userScore
 */
function GetUserSocreByUid($uid){

      $M = M('point','e_user_','ecrm');
      $where['user_id'] = $uid;
      // 把查询条件传入查询方法
      $point= $M->where($where)->find();
      if($point!=null || $point!=""){
            return $point['currency_point'];
      }else{
            return "暂未获得数据";
      }
}
/**
 * 通过uid
 * 获取用户的积分
 * @param uid $uid
 * @return userScore
 */
function GetUserTotalSocreByUid($uid){

      $M = M('point','e_user_','ecrm');
      $where['user_id'] = $uid;
      // 把查询条件传入查询方法
      $point= $M->where($where)->find();
      if($point!=null || $point!=""){
            return $point['total_currency'];
      }else{
            return 0;
      }
}
/*
 * 通过pid 获取 抽奖奖品信息
 *@param pid $pid
 */
function GetLottoInfoByPid($pid){
      // 把查询条件传入查询方法\
      $M = M('lotto','ny_prize_','newyear');
      $where['id'] = $pid;
      $prize= $M->where($where)->find();

      if($prize==null || $prize==""){
            return null;
      }else{
            return $prize;
      }

}
/*
 * 通过pid 获取 兑换奖品信息
 * *@param pid $pid
 */
function GetDuiInfoByPid($pid){
      // 把查询条件传入查询方法\
      $M = M('exchange','ny_prize_','newyear');
      $where['id'] = $pid;
      $prize= $M->where($where)->find();

      if($prize==null || $prize==""){
           return null;
      }else{
            return $prize;
      }

}
/*
 * 获取 今日 奖品 已经兑换的数量
 *  *@param pid $pid
 * @param $type 奖品类型 1 兑换 2 抽奖
 */
   function  GetTodayPrizeHave($pid,$type){
         $todayBegin = strtotime(date('Y-m-d') ."11:59:59");
         $tomorrBegin = strtotime(date("Y-m-d", strtotime("+1 day")) ."11:59:59");
         $nowDate=time();
         $yestEnd = strtotime(date("Y-m-d", strtotime("-1 day")) ."11:59:59");

         $M = M('prize','ny_act_','newyear');
         $wherePrize['pid'] =$pid;
         $wherePrize['type'] =$type;
         if($nowDate>$todayBegin){
               $wherePrize['subtime'] = array(array('EGT',$todayBegin),array('ELT',$tomorrBegin),'AND');
         }else{
               $wherePrize['subtime'] = array(array('EGT',$yestEnd),array('ELT',$todayBegin),'AND');
         }
         $result=$M->where($wherePrize)->select();
         return $result;
}



/**
 *获取 uid 是否兑换过 改奖品
 *  *@param pid $pid
 * @param type $type 奖品类型 1 兑换 2 抽奖
 */
function CheckIsDuiByPid($pid,$type){
      //检测他是否兑换过该奖品
      $Mod= M('prize','ny_act_','newyear');
      $where['uid'] = cookie('uid');
      $where['pid'] = $pid;
      $where['type'] = $type;
      $data= $Mod->where($where)->select();
      if(count($data)>=1){
            return true;
      }else{
            return false;
      }
}
//谢谢抽奖
function GetThanksAngle(){
      $thanks=array(
            '0' => array('pid'=>12,'min'=>array(10,192), 'max'=>array(40,212))
      );
      $angle=216;
      foreach($thanks as $k=>$val){
            $rand=  mt_rand(0,1);
            $result['min'] =  $val['min'][$rand];
            $result['max']= $val['max'][$rand];
            $angle=mt_rand($result['min'], $result['max']);
      }
         return $angle;
}

/**
 *
 * 奖品日志
 * @param uid 用户id
 */
  function  log_prize($pid){
      $M = M('act_log','ny_prize_','newyear');
      $log['uid'] = cookie("uid");
      $log['prizeid'] = $pid;
      $log['strip'] =get_client_ip();
      $log['addtime'] =time();
      $M->add($log);
}

/**
 *
 * ecrm itemID 日志
 * @param uid 用户id
 */
  function  Add_Log_ecrm_pointDetil($itemId,$socre){
      $M = M('pointdetail','e_user_','ecrm');
      $log['user_id'] = cookie("uid");
      $log['point_item_type'] = 1;
      $log['point_item_id'] = $itemId;
      $log['operator_type'] = 2;
      $log['point_value'] = $socre;
      $log['create_time'] =time();
      $M->add($log);
}

/*
 *
 * 兑换成功后 减少奖品数量
 *
 */

function pushNumByPid($pid,$left){
      //减少该奖品剩余数量
      $M = M('exchange','ny_prize_','newyear');
      $where['left']=$left-1;
      $res=$M->field('left')->where("id=".$pid)->save($where);
      return $res;
}

/*
 * 改兑换码的状态
 *
 */
function changeStatusByCode($id){
      $M = M('code','ny_prize_','newyear');
      $where['status']=1;
      $res=$M->field('status')->where("id=".$id)->save($where);
      return $res;
}
/*
 * 改url码的状态
 *
 */
function changeStatusByurl_code($id){
      $M = M('url','ny_prize_','newyear');
      $where['status']=1;
      $res=$M->field('status')->where("id=".$id)->save($where);
      return $res;
}

function changeStatusBymoney_code($id){
      $M = M('money','ny_prize_','newyear');
      $where['status']=1;
      $res=$M->field('status')->where("id=".$id)->save($where);
      return $res;
}
/*
 *
 * 抽奖成功后 减少奖品数量
 *
 */

function pushNumLottoByPid($pid,$left){
      //减少该奖品剩余数量
      $M = M('Lotto','ny_prize_','newyear');
      $where['id'] = $pid;
      $where['left']=$left-1;
      $res=$M->field('left')->where("id=".$pid)->save($where);
      return $res;
}
/*
 * 添加到礼品
 *
 */
function Add_log_user_prize($pid,$type,$code,$url_code,$mony_code){
      //兑换 记录 兑奖用户
      $M = M('prize','ny_act_','newyear');
      $actUser['pid'] = $pid;
      $actUser['uid'] = cookie("uid");
      $actUser['type'] = $type;
      if($code){
            $actUser['code'] = $code;
      }
      if($mony_code){
            $actUser['code'] = $mony_code;
      }
      if($url_code){
            $actUser['code_url'] = "<a href=".$url_code." target='view_window'>".$url_code."</a>";
      }
      $actUser['ismobie'] =  isMobile()==true?"手机端":"pc端";
      $actUser['subtime'] =time();
      return $id=$M->add($actUser);
}

/*
 * 扣除 用户积分
 *
 */
function Deduction_User_points($score){
      //扣除积分
      $currPoint= GetUserSocreByUid(cookie("uid"));
      $currPoint_total=GetUserTotalSocreByUid(cookie("uid"));
      $M = M('point','e_user_','ecrm');
      // 要修改的数据对象属性赋值
//      $where['user_id']=cookie("uid");
      $where['currency_point'] = $currPoint-$score;
      $where['total_currency'] = $currPoint_total-$score;
      $res= $M->where('user_id='.cookie("uid"))->field('currency_point,total_currency')->save($where); // 根据条件更新记录
      return $res;
}

// 获取兑换码 通过 pid
function GetCodeByPid(){
      $M = M('code','ny_prize_','newyear');
//      $where['prize_id']=$pid;
      $where['status']=0;
      $code=$M->where($where)->find();
      return $code;
}

function GetCodeUrlByPid(){
      $M = M('url','ny_prize_','newyear');
//      $where['prize_id']=$pid;
      $where['status']=0;
      $code=$M->where($where)->find();
      return $code;

}
/**
 * 获取所有的省
 */
  function  getAllPro(){
      $M = M('linkage','cms_','newyear');
      $where['parentid'] = 0;
      $result=  $M->cache(true)->where($where)->select();
      return $result;
}

/**
 * 获取所有的市
 * proid
 */
  function  getAllCity($proid){
      $M = M('linkage','cms_','newyear');
      $where['parentid'] =$proid;
      $result=  $M->cache(true)->where($where)->select();
      return $result;
}

/*
 *
 * 获取经销商的省
 */
function get_dealer_privince(){
    $M = M('info','dealer_','newyear');
    $result=$M->cache(true)->group('privince')->order('convert(privince using gb2312)')->select();
    return $result;
}

/*
 *
 * 获取经销商的省
 */
function get_dealer_city_from_privince($privince){
    $M = M('info','dealer_','newyear');
    $where['privince'] = $privince;
    $result=$M->cache(true)->where($where)->group('city')->order('convert(city using gb2312)')->select();
    return $result;
}

/*
 *
 * 获取经销商的市
 */
  function get_dealer_city(){
        $M = M('info','dealer_','newyear');
        $result=$M->cache(true)->group('city')->order('convert(city using gb2312)')->select();
        return $result;
  }

/*
 *
 * 获取经销商的信息
 */
function get_dealer_info($city){
      $M = M('info','dealer_','newyear');
      $where['city']=$city;
      $result=$M->cache(true)->where($where)->select();
      return $result;

}
/*
 *
 * 保存用户邮寄的信息
 */
function Save_Address($phone,$user_turename,$address){

    $M = M('user','ny_','newyear');
    $data['user_turename']=$user_turename;
    $data['phone']=$phone;
    $data['address']=$address;
    $code=$M->where("id=".cookie("uid"))->save($data);
    return $code;
}
/*
 *
 * 获取用户的奖品信息
 */
function get_user_act_prize(){

    $pages = array();
    $M= M('prize','ny_act_','newyear');
    $where['uid'] = cookie('uid');
    $count      = $M->where($where)->count();// 查询满足要求的总记录数
    $Page       = new \Think\PageEx($count,5);// 实例化分页类 传入总记录数和每页显示的记录数(25)
    $show       = $Page->show();// 分页显示输出
    // 进行分页数据查询 注意limit方法的参数要使用Page类的属性
    $prizes = $M->where($where)->order('subtime')->limit($Page->firstRow.','.$Page->listRows)->select();

    $pages['show'] = $show;
    $pages['prizes'] = $prizes;
    return $pages;
}
/*
 *
 * 获取用户的奖品信息_移动端
 */
function get_user_act_prize_mobile(){

    $pages = array();
    $M= M('prize','ny_act_','newyear');
    $where['uid'] = cookie('uid');
    $count      = $M->where($where)->count();// 查询满足要求的总记录数
    $Page       = new \Think\PageMobile($count,2);// 实例化分页类 传入总记录数和每页显示的记录数(25)
    $show       = $Page->show();// 分页显示输出
    // 进行分页数据查询 注意limit方法的参数要使用Page类的属性
    $prizes = $M->where($where)->order('subtime')->limit($Page->firstRow.','.$Page->listRows)->select();

    $pages['show'] = $show;
    $pages['prizes'] = $prizes;
    return $pages;
}
/*
 *
 * 获取所有的获奖信息
 */
function get_all_act_prize(){

    $pages = array();
    $M= M('prize','ny_act_','newyear');
    $count      = $M->where(" type=2 ")->count();// 查询满足要求的总记录数
    $Page       = new \Think\PageEx($count,10);// 实例化分页类 传入总记录数和每页显示的记录数(25)
    $show       = $Page->show();// 分页显示输出
    // 进行分页数据查询 注意limit方法的参数要使用Page类的属性
    $prizes = $M->where(' type=2 ')->order('subtime')->limit($Page->firstRow.','.$Page->listRows)->select();

    $pages['show'] = $show;
    $pages['prizes'] = $prizes;
    return $pages;
}

/*
 *
 * 获取所有的获奖信息_移动端
 */
function get_all_act_prize_mobile(){

    $pages = array();
    $M= M('prize','ny_act_','newyear');
    $count      = $M->where(" type=2 ")->count();// 查询满足要求的总记录数
    $Page       = new \Think\PageMobile($count,10);// 实例化分页类 传入总记录数和每页显示的记录数(25)
    $show       = $Page->show();// 分页显示输出
    // 进行分页数据查询 注意limit方法的参数要使用Page类的属性
    $prizes = $M->where(" type=2 ")->order('subtime')->limit($Page->firstRow.','.$Page->listRows)->select();

    $pages['show'] = $show;
    $pages['prizes'] = $prizes;
    return $pages;
}

/*
 * 获取所有的兑换奖品信息
 *
 */
function get_All_DuihuanPirzeInfo(){

      $M= M('exchange','ny_prize_','newyear');
      $data= $M->order("id not in(12,13), score desc")->select();
      return $data;
}

/*
 * GetMoneyCodeByNum
 *
 */
function GetMoneyCodeByNum($numType){
      $M = M('money','ny_prize_','newyear');
//      $where['prize_id']=$pid;
      $where['status']=0;
      $where['money_type']=$numType;
      $code=$M->where($where)->find();
      return $code;

}

//创建TOKEN
function creatToken() {
      $code = chr(mt_rand(0xB0, 0xF7)) . chr(mt_rand(0xA1, 0xFE)) . chr(mt_rand(0xB0, 0xF7)) . chr(mt_rand(0xA1, 0xFE)) . chr(mt_rand(0xB0, 0xF7)) . chr(mt_rand(0xA1, 0xFE));
      session('TOKEN', authcode($code));
      return authcode($code);
}

//判断TOKEN
function checkToken($token) {
      if ($token == session('TOKEN')) {
            session('TOKEN', NULL);
            return TRUE;
      } else {
            return FALSE;
      }
}

/* 加密TOKEN */
function authcode($str) {
      $key = "ANDIAMON";
      $str = substr(md5($str), 8, 10);
      return md5($key . $str);
}
/**
 * 参数解密
 * @param $val
 */
 function appParamBase64Decode($val, $defVal = ' ') {
      if (empty ( $val )) {
            return $defVal;
      }
      $val = trim ( $val );
      $len = strlen ( $val );
      // 首尾调换
      $val =  substr ( $val, - 1, 1 ) . substr ( $val, 1, $len - 2 ) . substr ( $val, 0, 1 );
      // 解码
      $val = base64_decode ( $val );
      return $val;
}
